package com.lorenzogao.pley.common.rx

import com.lorenzogao.pley.bean.BaseBean
import com.lorenzogao.pley.common.exception.ApiException
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * 作者：Lorenzo Gao
 * Date: 2017/12/29
 * Time: 13:10
 * 邮箱：2508719070@qq.com
 * Description:
 */
class RxHttpReponseCompat {

    companion object {
        //
        fun <T> compatResult(): ObservableTransformer<BaseBean<T>, T> {

            return ObservableTransformer { baseBeanObservable ->
                return@ObservableTransformer baseBeanObservable.flatMap<T> { tBaseBean ->
                    if (tBaseBean.success()) {

                        return@flatMap Observable.create<T> { subscriber ->
                            try {
                                subscriber.onNext(tBaseBean.data)
                                subscriber.onComplete()
                            } catch (e: Exception) {
                                subscriber.onError(e)
                            }
                        }
                    } else {
                        return@flatMap Observable.error(ApiException(tBaseBean.status, tBaseBean.message))
                    }
                }.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
            }

        }

//        fun <T> compatResult(): ObservableTransformer<BaseBean<T>, T> {
//
//            return ObservableTransformer {
//
//                baseBeanObservable ->
//                return@ObservableTransformer baseBeanObservable.flatMap(Function<BaseBean<T>, Observable<T>> { tBaseBean ->
//                    if (tBaseBean.success()) {
//                        return@Function Observable.create({ subscribe ->
//                            try {
//                                subscribe.onNext(tBaseBean.data)
//                                subscribe.onCompleted()
//                            } catch (e: Exception) {
//                                subscribe.onError(e)
//                            }
//                        })
//                    } else {
//                        return@Function  Observable.error<T>(ApiException(tBaseBean.status, tBaseBean.message))
//                    }
//
//                }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
//            }
//
//        }


    }


}